<?php
namespace app\common\controller;
use think\Db;
use think\Config;
use think\Cache;
class mpweixin{
    public $appid;
    public $secret;
    public $access_token;
    public $wx_id;
    public function __construct($config){
        $this->appid = $config['appid'];
        $this->secret = $config['secret'];
        $this->wx_id=$config['secret']=$config['type'];
        $this->access_token = $this->getAccessToken();
    }
    /* ----------------------------------响应----------------------------- */
    /**
     * 响应消息
     */
    public function responseMsg()
    {
        $postStr = file_get_contents("php://input");
        if (!empty($postStr)){
            //$this->logger("R \r\n".$postStr);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);

            switch ($RX_TYPE)
            {
                // 事件
                case "event":
                    $result = $this->receiveEvent($postObj);
                    break;
                // 文本
                case "text":
                    $result = $this->receiveText($postObj);
                    break;
                // 图片
                case "image":
                    $result = $this->receiveImage($postObj);
                    break;
                // 地理位置
                case "location":
                    $result = $this->receiveLocation($postObj);
                    break;
                // 语音
                case "voice":
                    $result = $this->receiveVoice($postObj);
                    break;
                // 视频
                case "video":
                    $result = $this->receiveVideo($postObj);
                    break;
                // 链接
                case "link":
                    $result = $this->receiveLink($postObj);
                    break;
                default:
                    $result = "unknown msg type: ".$RX_TYPE;
                    break;
            }
            $this->logger("T \r\n".$result);
            echo $result;
        }else {
            echo "";
            exit;
        }
    }
    /* ----------------------------------接收----------------------------- */
    /**
     * 接收事件消息
     */
    private function receiveEvent($object)
    {
        switch ($object->Event)
        {
            // 关注时的事件推送
            case "subscribe":
//                preg_match('/\d+/',$object->EventKey,$arr);
//                if (strpos($object->EventKey,'9999') !== false){
//                    $data=Db::name('admin')->where(['wx_token'=>$object->FromUserName,'status'=>'normal'])->find();
//                    session('openId',$object->FromUserName);
//                    if ($data){
//                        $this->transmitText_gzsc($object,'您已成功登录高考早知道后台,如非本人操作请联系管理员！');
//                    }
//                }
                if ($object->EventKey ){
                    preg_match('/\d+/',$object->EventKey,$arr);
                    Db::name('admin_scan')->insert(['open_id'=>$object->FromUserName,'state'=>$arr[0],'time'=>time()]);
                    $data=Db::name('admin')->where(['wx_token'=>$object->FromUserName,'status'=>'normal'])->find();
                    if ($data){
                        $content='您已成功登录高考早知道后台,如非本人操作请联系管理员！';
                    }else{
                        $content='您已扫码成功,请完成账号绑定';
                    }
                }
                break;
            // 取消关注事件
            case "unsubscribe":
                $content = "取消关注";
                break;
            // 点击菜单拉取消息时的事件推送
            case "CLICK":
                switch ($object->EventKey)
                {
                    case "COMPANY":
                        $content = array();
                        $content[] = array("Title"=>"福建高考", "Description"=>"", "PicUrl"=>"", "Url" =>"http://www.fjgkedu.com");
            break;
                    default:
                        $content = "点击菜单：".$object->EventKey;
                        break;
                }
                break;
            // 点击菜单跳转链接时的事件推送
            case "VIEW":
                $content = "跳转链接 ".$object->EventKey;
                break;
            // 扫描带参数二维码场景，用户已关注时的事件推送
            case "SCAN":
                $content='扫码成功!';
                if ($object->EventKey && $object->EventKey>0){

                    Db::name('admin_scan')->insert(['open_id'=>$object->FromUserName,'state'=>$object->EventKey,'time'=>time()]);
                    $data=Db::name('admin')->where(['wx_token'=>$object->FromUserName,'status'=>'normal'])->find();
                    if ($data){
//                        Db::name('wx_test')->insert(['content'=>json_encode($this->getUserInfo($object->FromUserName,$this->getAccessToken()))]);
                        $content='您已成功登录高考早知道后台,如非本人操作请联系管理员！';
                    }else{
                        $content='您已扫码成功,请完成账号绑定';
                    }
                }
//                exit;
//                $this->transmitText_gzsc($object,$object->EventKey);
                break;
            // 上报地理位置事件
            case "LOCATION":
                $content = "上传位置：纬度 ".$object->Latitude.";经度 ".$object->Longitude;
                break;
            // 扫码推事件且弹出“消息接收中”提示框的事件推送
            case "scancode_waitmsg":
                if ($object->ScanCodeInfo->ScanType == "qrcode"){
                    $content = "扫码带提示：类型 二维码 结果：".$object->ScanCodeInfo->ScanResult;
                }else if ($object->ScanCodeInfo->ScanType == "barcode"){
                    $codeinfo = explode(",",strval($object->ScanCodeInfo->ScanResult));
                    $codeValue = $codeinfo[1];
                    $content = "扫码带提示：类型 条形码 结果：".$codeValue;
                }else{
                    $content = "扫码带提示：类型 ".$object->ScanCodeInfo->ScanType." 结果：".$object->ScanCodeInfo->ScanResult;
                }
                break;
            // 扫码推事件的事件推送
            case "scancode_push":
                $content = "扫码推事件";
                break;
            // 弹出系统拍照发图的事件推送
            case "pic_sysphoto":
                $content = "系统拍照";
                break;
            // 弹出微信相册发图器的事件推送
            case "pic_weixin":
                $content = "相册发图：数量 ".$object->SendPicsInfo->Count;
                break;
            // 弹出拍照或者相册发图的事件推送
            case "pic_photo_or_album":
                $content = "拍照或者相册：数量 ".$object->SendPicsInfo->Count;
                break;
            // 弹出地理位置选择器的事件推送
            case "location_select":
                $content = "发送位置：标签 ".$object->SendLocationInfo->Label;
                break;
            // 点击菜单跳转小程序的事件推送
            case "view_miniprogram":
                $content = "SUCCESS";
                break;
            default:
                $content = "receive a new event: ".$object->Event;
                break;
        }
        if(is_array($content)){
            if (isset($content[0]['PicUrl'])){
                $result = $this->transmitNews($object, $content);
            }else if (isset($content['MusicUrl'])){
                $result = $this->transmitMusic($object, $content);
            }
        }else{
            $result = $this->transmitText($object, $content);
        }
        return $result;
    }

    private function transmitText_gzsc($object, $content) //高招商城扫码专用
    {
        if (!$object->EventKey) {
            return "";
        }
        if (!isset($content) || empty($content)) {
            return "";
        }
        $xmlTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[text]]></MsgType>
            <Content><![CDATA[%s]]></Content>
          </xml>";
        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        return $result;
    }


    private function transmitText_gjc($object, $content) //高招商城扫码专用
    {
        if (!isset($content) || empty($content)) {
            return "";
        }
        $xmlTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[text]]></MsgType>
            <Content><![CDATA[%s]]></Content>
          </xml>";
        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        return $result;
    }
    /**
     * 接收文本消息
     */
    private function receiveText($object)
    {
        $keyword = trim($object->Content);
//        return $result;
    }
    /**
     * 接收图片消息
     */
    private function receiveImage($object)
    {
        $content = array("MediaId"=>$object->MediaId);
        $result = $this->transmitImage($object, $content);
        return $result;
    }
    /**
     * 接收位置消息
     */
    private function receiveLocation($object)
    {
        $content = "你发送的是位置，经度为：".$object->Location_Y."；纬度为：".$object->Location_X."；缩放级别为：".$object->Scale."；位置为：".$object->Label;
        $result = $this->transmitText($object, $content);
        return $result;
    }
    /**
     * 接收语音消息
     */
    private function receiveVoice($object)
    {
        if (isset($object->Recognition) && !empty($object->Recognition)){
            $content = "你刚才说的是：".$object->Recognition;
            $result = $this->transmitText($object, $content);
        }else{
            $content = array("MediaId"=>$object->MediaId);
            $result = $this->transmitVoice($object, $content);
        }
        return $result;
    }
    /**
     * 接收视频消息
     */
    private function receiveVideo($object)
    {
        $content = array("MediaId"=>$object->MediaId, "ThumbMediaId"=>$object->ThumbMediaId, "Title"=>"", "Description"=>"");
        $result = $this->transmitVideo($object, $content);
        return $result;
    }
    /**
     * 接收链接消息
     */
    private function receiveLink($object)
    {
        $content = "你发送的是链接，标题为：".$object->Title."；内容为：".$object->Description."；链接地址为：".$object->Url;
        $result = $this->transmitText($object, $content);
        return $result;
    }
    /* ----------------------------------回复----------------------------- */
    /**
     * 回复文本消息
     */
    private function transmitText($object, $content)
    {
        if (!isset($content) || empty($content)) {
            return "";
        }
        $xmlTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[text]]></MsgType>
            <Content><![CDATA[%s]]></Content>
          </xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        return $result;
    }

    /**
     * 文本回复图片
     */
    private function transmitImage_text($object, $imageArray)
    {
        $itemTpl = "<Image>
            <MediaId><![CDATA[%s]]></MediaId>
          </Image>";
        $item_str = sprintf($itemTpl, $imageArray);
        $xmlTpl =  "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[image]]></MsgType>
            $item_str
          </xml>";
        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;

    }
    /**
     * 回复多客服消息
     */
    private function transmitService($object)
    {
        $xmlTpl =  "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[transfer_customer_service]]></MsgType>
          </xml>";
        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }
    /**
     * 回复图文消息
     */
    private function transmitNews($object, $newsArray)
    {
        if(!is_array($newsArray)){
            return "";
        }
        $itemTpl = "<item>
            <Title><![CDATA[%s]]></Title>
            <Description><![CDATA[%s]]></Description>
            <PicUrl><![CDATA[%s]]></PicUrl>
            <Url><![CDATA[%s]]></Url>
          </item>";
        $item_str = "";
        foreach ($newsArray as $item){
            $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
        }
        $xmlTpl =  "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[news]]></MsgType>
            <ArticleCount>%s</ArticleCount>
            <Articles>$item_str</Articles>
          </xml>";
        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
        return $result;
    }
    /**
     * 回复音乐消息
     */
    private function transmitMusic($object, $musicArray)
    {
        if(!is_array($musicArray)){
            return "";
        }
        $itemTpl = "<Music>
            <Title><![CDATA[%s]]></Title>
            <Description><![CDATA[%s]]></Description>
            <MusicUrl><![CDATA[%s]]></MusicUrl>
            <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
          </Music>";
        $item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);
        $xmlTpl =  "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[music]]></MsgType>
            $item_str
          </xml>";
        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }
    /**
     * 回复图片消息
     */
    private function transmitImage($object, $imageArray)
    {
        $itemTpl = "<Image>
            <MediaId><![CDATA[%s]]></MediaId>
          </Image>";
        $item_str = sprintf($itemTpl, $imageArray['MediaId']);
        $xmlTpl =  "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[image]]></MsgType>
            $item_str
          </xml>";
        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    private function transmitImage1($object, $imageArray)
    {
        $itemTpl = "<Image>
            <MediaId><![CDATA[%s]]></MediaId>
          </Image>";
        $item_str = sprintf($itemTpl, $imageArray);
        $xmlTpl =  "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[image]]></MsgType>
            $item_str
          </xml>";
        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }
    /**
     * 回复语音消息
     */
    private function transmitVoice($object, $voiceArray)
    {
        $itemTpl = "<Voice>
            <MediaId><![CDATA[%s]]></MediaId>
          </Voice>";
        $item_str = sprintf($itemTpl, $voiceArray['MediaId']);
        $xmlTpl =  "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[voice]]></MsgType>
            $item_str
          </xml>";
        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }
    /**
     * 回复视频消息
     */
    private function transmitVideo($object, $videoArray)
    {
        $itemTpl = "<Video>
            <MediaId><![CDATA[%s]]></MediaId>
            <ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
            <Title><![CDATA[%s]]></Title>
            <Description><![CDATA[%s]]></Description>
          </Video>";
        $item_str = sprintf($itemTpl, $videoArray['MediaId'], $videoArray['ThumbMediaId'], $videoArray['Title'], $videoArray['Description']);
        $xmlTpl =  "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[video]]></MsgType>
            $item_str
          </xml>";
        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }
    /* ----------------------------------通用----------------------------- */
    /**
     * 回复第三方接口消息
     */
    private function relayPart3($url, $rawData)
    {
        $headers = array("Content-Type: text/xml; charset=utf-8");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $rawData);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
    /**
     * 字节转Emoji表情
     */
    function bytes_to_emoji($cp)
    {
        if ($cp > 0x10000){    # 4 bytes
            return chr(0xF0 | (($cp & 0x1C0000) >> 18)).chr(0x80 | (($cp & 0x3F000) >> 12)).chr(0x80 | (($cp & 0xFC0) >> 6)).chr(0x80 | ($cp & 0x3F));
        }else if ($cp > 0x800){  # 3 bytes
            return chr(0xE0 | (($cp & 0xF000) >> 12)).chr(0x80 | (($cp & 0xFC0) >> 6)).chr(0x80 | ($cp & 0x3F));
        }else if ($cp > 0x80){  # 2 bytes
            return chr(0xC0 | (($cp & 0x7C0) >> 6)).chr(0x80 | ($cp & 0x3F));
        }else{          # 1 byte
            return chr($cp);
        }
    }
    /**
     * 日志记录
     */
    private function logger($log_content)
    {
        if (isset($_SERVER['HTTP_APPNAME'])) {  //SAE
            sae_set_display_errors(false);
            sae_debug($log_content);
            sae_set_display_errors(true);
        } else if ($_SERVER['REMOTE_ADDR'] != "127.0.0.1") { //LOCAL
            $max_size = 1000000;
            $log_filename = "mpweixin.log.xml";
            try {
                if (file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)) {
                    unlink($log_filename);
                }
                file_put_contents($log_filename, date('Y-m-d H:i:s')." ".$log_content."\r\n", FILE_APPEND);
            } catch (\Exception $e) {
                return $e->getMessage();
                exit();
            }

        }
    }
    /**
     * 获取access_token
     */
    private function getAccessToken($new=0)
    {
//        $token= Cache::get('token');
//        if ($token){
//            return $token;
//        } else{
//            $token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->appid . "&secret=" . $this->secret;
//            $response = $this->get_contents($token_url);
//            $params = array();
//            $params = json_decode($response,true);
//            if (isset($params['errcode']))
//            {
//                echo "<h3>error:</h3>" . $params['errcode'];
//                echo "<h3>msg :</h3>" . $params['errmsg'];
//                exit;
//            }
//            Cache::set('token',$params['access_token'],3600);
//            return $params['access_token'];
//        }
        if($new){
            $url="http://www.gkzzd.com/Wx/getAccessToken";
        }else{
            $url="http://www.gkzzd.com/Wx/getAccessToken?new=1";
        }

        $rs= json_decode($this->curlGet($url),true);
        return $rs['data'];
    }

    public function get_contents($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_URL, $url);
        $response = curl_exec($ch);
        curl_close($ch);
        //-------请求为空
        if(empty($response)){
            exit("50001");
        }
        return $response;
    }

    public static function curlGet($url = '', $options = array())
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    public function getUserInfo($openid,$access_token)
    {
        //$response = $this->curlGet('https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN');
        $response = $this->curlGet('https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN');
        return json_decode($response,true);

    }

    public function merge($posterImgPath, $tmpFile){
       $img = new GreatePoster();
        // 头像与国旗，我们给它限制一下大小
        $image1 = $img->CreateImage($posterImgPath, 960, 960);
        $image2 = $img->CreateImage($tmpFile, 320, 320, 600, 600);

        // 设置自定义-指定宽度来计算点位
        $config = [
            'dst_x' => 640,
            'dst_y' => 640,
            'src_x' => 0,
            'src_y' => 0,
            'src_w' => 320,
            'src_h' => 320,
            'pct'   => 100,
        ];

        // 合成海报底图跟二维码
       $img->ImagesMerge($image1, $image2, $config);
       $img->look($image1); // 浏览图片

    }
    public function uploadImg($imgUrl){

        $TOKEN=$this->getAccessToken();
//                https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE
//        $URL ='http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token='.$TOKEN.'&type=image';
        $URL ='https://api.weixin.qq.com/cgi-bin/media/upload?access_token='.$TOKEN.'&type=image';
//        $data = array('media'=>'@'.$imgUrl);
        if(class_exists('\CURLFile')){
            $data = ['media' => new \CURLFile($imgUrl)];
        }else{
            $data = ['media' => "@$imgUrl"];
        }
        $result = $this->curl_post($URL,$data);
        unlink($imgUrl);
        $data = @json_decode($result,true);
        return $data['media_id'];
    }

    public function materialImg($imgUrl){

        $TOKEN=$this->getAccessToken();
        $URL ='https://api.weixin.qq.com/cgi-bin/material/add_material?access_token='.$TOKEN.'&type=image';
//        $data = array('media'=>'@'.$imgUrl);
        if(class_exists('\CURLFile')){
            $data = ['media' => new \CURLFile($imgUrl)];
        }else{
            $data = ['media' => "@$imgUrl"];
        }
        $result = $this->curl_post($URL,$data);
        unlink($imgUrl);
        $data = @json_decode($result,true);
        return $data['media_id'];
    }

    public function curl_post($url, $data = null)
    {
        //创建一个新cURL资源
        $curl = curl_init();
        //设置URL和相应的选项
        curl_setopt($curl, CURLOPT_URL, $url);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //执行curl，抓取URL并把它传递给浏览器
        $output = curl_exec($curl);
        //关闭cURL资源，并且释放系统资源
        curl_close($curl);
        return $output;
    }


    public function saveImage($path) {
        $id=time().rand(1000,9999);
        $image_name=ROOT_PATH . 'public' . DS ."static/upload/".time().rand(1000,9999).".jpg";

//        $image_name = "static/upload/".$id.".jpg";
        $ch = curl_init ($path);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
        $img = curl_exec ($ch);
        curl_close ($ch);
        $fp = fopen($image_name,'w');
        fwrite($fp, $img);
        fclose($fp);
        return $image_name;
    }

    public function complex($head,$type){
        if ($type==1){
            $cap=ROOT_PATH . 'public' . DS .'static/images/cap_zq.png';
        }elseif($type==5){
            $cap=ROOT_PATH . 'public' . DS .'static/images/cap_zy.png';
        }
        else{
//            $cap=ROOT_PATH . 'public' . DS .'static/images/new_tree.png';
            $cap=ROOT_PATH . 'public' . DS .'static/images/cap_gq.png';//状元帽
        }
        $src = imagecreatefromstring(file_get_contents($head));
//创建点的实例
        $des = imagecreatefrompng($cap);
//获取点图片的宽高
        list($point_w, $point_h) = getimagesize($cap);//获取点图片的宽高
        list($point_w1, $point_h1) = getimagesize($head);//获取点图片的宽高
        imagecopyresampled($src, $des,0,0,0,0,$point_w1,$point_h1,$point_w,$point_h);
     //   header('Content-Type: image/jpeg');
        $new=ROOT_PATH . 'public' . DS ."static/upload/".time().rand(1000,9999).".jpg";
        imagejpeg($src,$new,85);
//        unlink($head);
        if ($type==1){
            unlink($head);
        }
        imagedestroy($src);
        imagedestroy($des);
        return $new;

    }
    private function messageToUserName_xcx($content,$fromUsername,$media)//content 就是回复的消息，$fromUsername就是openid
    {
//这里要获取token
        $ACC_TOKEN = $this->getAccessToken();
        $data = '{
        "touser":"'.$fromUsername.'",
        "msgtype":"miniprogrampage",
        "miniprogrampage":
        {
        "title":"新高考选课-院校匹配",
        "appid":"wx155a07475f8ffb49",
        "pagepath":"'.$content.'",
        "thumb_media_id":"'.$media.'"
            }
            }';

        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$ACC_TOKEN;

        $result = $this->https_post($url,$data);
//        $final = json_decode($result);
//        return $final;
    }
    private function messageToUserName_txt($content,$fromUsername)//content 就是回复的消息，$fromUsername就是openid
    {
//这里要获取token
        $ACC_TOKEN = $this->getAccessToken();
        $data = '{
        "touser":"'.$fromUsername.'",
        "msgtype":"text",
        "text":
        {
        "content":"'.$content.'"
            }
            }';

        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$ACC_TOKEN;

        $result = $this->https_post($url,$data);
        $final = json_decode($result);
        return $final;
    }
    private function messageToUserName($content,$fromUsername)//content 就是回复的消息，$fromUsername就是openid
    {
//这里要获取token
        $ACC_TOKEN = $this->getAccessToken();
        $data = '{
            "touser":"'.$fromUsername.'",
            "msgtype":"image",
            "image":
            {
            "media_id":"'.$content.'"
            }
            }';

        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$ACC_TOKEN;
        $result = $this->https_post($url,$data);
        $final = json_decode($result);
        return $final;
    }
    public function https_post($url,$data)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        if (curl_errno($curl)) {
            return 'Errno'.curl_error($curl);
        }
        curl_close($curl);
        return $result;
    }

    public function getEwm($code,$type){
        $url = $this->getQrcodeurl($code,$type);
        return $url;
//        $this->DownLoadQr($url,time());
    }
    protected function getQrcodeurl($fqid,$type){
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$this->access_token."";
        //生成临时二维码

        if($type == 1){
            //生成永久二维码
            $qrcode= '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": '.$fqid.'}}}';

        }else{
            //生成临时二维码
            $qrcode = '{"expire_seconds": 7200, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_str": '.$fqid.'}}}';
        }


        $result = $this->https_post($url,$qrcode);

        $oo = json_decode($result,true);
        $ticket=UrlEncode($oo['ticket']);
        $url_ticket = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$ticket."";
        return $url_ticket;
    }
    public function getEwm_1($code){
        $url = $this->getQrcodeurl1($code);
        return $url;
    }
    protected function getQrcodeurl1($code){
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$this->access_token."";
            //生成临时二维码
//        $qrcode = '{"expire_seconds": 7200, "action_name": "QR_STR_SCENE", "action_info": {"scene": {"scene_str": "'.$code.'"}}}';
        $qrcode =   '{"expire_seconds": 7200, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": '.$code.'}}}';
//dump($this->access_token);exit;
        $result = $this->https_post($url,$qrcode);
        $oo = json_decode($result,true);
        if(!isset($oo['ticket'])){
            $this->getAccessToken(1);
            $this->getQrcodeurl1($code);
        }
        $ticket=UrlEncode($oo['ticket']);
        $url_ticket = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$ticket."";
        return $url_ticket;
    }
    //下载二维码到服务器
    protected function DownLoadQr($url,$filestring){
        if($url == ""){
            return false;
        }
        $filename = $filestring.rand(0,99999999999).'.jpg';
        ob_start();
        readfile($url);
        $img=ob_get_contents();
        ob_end_clean();
        $size=strlen($img);
        $fp2=fopen('static/sd/'.$filename,"a");
        if(fwrite($fp2,$img) === false){
            echo 'dolwload image falied. Error Info: 无法写入图片';
            exit();
        }
        fclose($fp2);
        return 'static/sd/'.$filename;
    }


    public function mass_wx ($open_id,$text){ //高招群发消息
        $this->messageToUserName_txt($text,$open_id);
    }



}